﻿using Entity.Models;
using HuaRunInterface.Comm;
using HuaRunInterface.Models;
using Microsoft.AspNetCore.Mvc;
using Utility;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace HuaRunInterface.Controllers.AddControllers
{
    [Route("api/HuaRun/[controller]")]
    [ApiController]
    public class AddRTUInfoController : ControllerBase
    {
        // POST api/<AddRTUInfoController>
        [HttpPost]
        public object Post([FromBody] RTUInfo value)
        {
            return AddData(value);
        }

        private object AddData(RTUInfo dto)
        {
            ReturnData rd = new ReturnData();

            try
            {
                string conn = Global.Configuration["ConnectionStrings:DDb"];
                using (Entity.DBContext context = Entity.BaseContext.CreateContext(conn))
                {
                    var v = context.rTUInfos.Where(p => p.deviceCode == dto.deviceCode && p.IsDelete != 1).FirstOrDefault();
                    if (v != null)
                    {
                        throw new Exception("设备编码不能重复添加！");
                    }
                    dto.sequence = "RTU" + DateTime.Now.ToString("yyyyMMddHHmmssff");
                    dto.factoryCode = Global.Configuration["AppSettings:FactoryCode"];
                    dto.domainId = Global.DomainId;
                    dto.CreateDate = DateTime.Now;
                    context.rTUInfos.Add(dto);

                    string msg = "";
                    RTURegisterModel model = dto.SerializerObjectToString().JSONStringToObject<RTURegisterModel>();
                    bool mr = Global.RTURegister(model, ref msg);
                    if (mr)
                    {
                        context.SaveChanges();
                    }
                    rd.State = mr ? "success" : "failed";
                    rd.Message = msg;
                }
            }
            catch (Exception ex)
            {
                rd.State = "failed";
                rd.Message = ex.Message;
                rd.Data = ex.StackTrace;
            }
            return rd;
        }
    }
}
